const localviedo = document.getElementById('localvideo')
const remoteviedo = document.getElementById('remotevideo')
const startBtn = document.getElementById('start')
const callBtn = document.getElementById('call')
const hangupBtn = document.getElementById('hangup')
const offer_txt = document.getElementById('offer_txt')
const answer_txt = document.getElementById('answer_txt')
let localStream;
let pc1;
let pc2;

startBtn.onclick =  start;
callBtn.onclick =  call
hangupBtn.onclick =  hangup

function start(){
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
        console.log('getUserMedia is not support');
        return;
    }else{
        const option = {
            video:true,
            audio:true
        }
        navigator.mediaDevices.getUserMedia(option).then(getMediaStream).catch(handleError)
    }
}

function getMediaStream(stream){
    localviedo.srcObject = stream
    localStream =stream

}
function handleError(){
    console.log('fail to get strem');
}

function call(){
    pc1 = new RTCPeerConnection()
    pc2 = new RTCPeerConnection()
    pc1.onicecandidate = (e) => {
        pc2.addIceCandidate(e.candidate)
    }

    pc2.onicecandidate = (e) => {
        pc1.addIceCandidate(e.candidate)
    }
    pc2.ontrack = getRemoteStream

    localStream.getTracks().forEach((track)=>{
        pc1.addTrack(track,localStream)
    })
    // 创建媒体协商
    const offerOpt = {
        offerToReceiveAudio:true,
        offerToReceiveVideo:true
    }
    pc1.createOffer(offerOpt).then(getOffer).catch(errorOffer)
}

function getRemoteStream(e){
    remoteviedo.srcObject = e.streams[0];
}

function getOffer(desc){
    pc1.setLocalDescription(desc)
    offer_txt.value = desc.sdp

    // 发送desc到signal服务器，pc2从signal上接受到desc
    pc2.setRemoteDescription(desc)
    // pc2接受到pc1的desc后，创建自己的answer
    pc2.createAnswer().then(getAnswer).catch(errorAnswer)
}

function getAnswer(desc){
    answer_txt.value = desc.sdp
    pc2.setLocalDescription(desc)
    pc1.setRemoteDescription(desc)
}

function errorOffer(err){
    console.error('offer:',err)
}
function errorAnswer(err){
    console.error('answer:',err)
}

function hangup(){
    pc1.close()
    pc1= null;
    pc2.close()
    pc2=null;
}
